// pages/index/bindingBeeper/index.js
const $api = require('../../../request/api').API;
import Toast from '../../../miniprogram_npm/@vant/weapp/toast/toast';
import { deEmptyChildrenCascader, findPathDFS } from '../../../utils/hooks';
import * as Storage from '../../../utils/storage';
import { getAddress } from '../../../utils/util';
const app = getApp();
/**
 * addressType地址类型的值：
 *{ id: 5, name: "用户新地址" }, //
 *{ id: 1, name: "呼叫器地址及联系人" },//
 *{ id: 2, name: "呼叫器地址和下单联系人" },
 *{ id: 3, name: "符合条件的就近收货地址" },
 *{ id: 4, name: "呼叫器地址和门牌号" },
 *{ id: 6, name: "呼叫器地址和层、门牌号" },
 *{ id: 7, name: "呼叫器地址和单元、层、门牌号" },
 *{ id: 8, name: "呼叫器地址和栋、单元、层、门牌号" },
 *
 */
Page({
  data: {
    equipId: '',
    beeperId: '',
    equipType: '',
    equipCode: '',
    beeperAddress: '', //湖南省长沙市望城区金星北路三段387号明发国际公馆B座(测试数据)
    existZhu: false,
    beeperType: '', //1是公用版，2是专用版
    beeperVersion: '', //1是虚拟版 2、3、4是实体版
    columnsCS: [],
    columnsQY: ['客厅', '主卧', '次卧', '儿童房', '书房', '厨房', '阳台', '卫生间', '自定义区域'],
    localeId: '',
    localeName: '',
    latitude: 0,
    longitude: 0,
    houseNumber: '',
    houseNumberId: '',
    areaIndex: '',
    installArea: '',
    linkName: '',
    phone: '',
    showCustomArea: '', //是否显示自定义区域,
    showCustomLocale: '', //是否显示自定义场所
    beeperBinding: '', //是否已经绑定，有值就绑定了，没有值就没有绑定
    beeperCode: '',
    loading: true,
    addressType: '', // 地址类型
    residentAddressValue: '',
    residentAddressName: '',
    residentAddressList: [],
    residentAddressOptions: [],
    residentAddressTitle: '',
    showResidentAddress: false,
    residentFieldNames: {
      text: 'name',
      value: 'id'
    },
    buildId: '',
    buildName: '',
    unitId: '',
    unitName: '',
    floorId: '',
    floorName: '',
    provinceName: '',
    cityName: '',
    areaName: '',
    streetName: '',
    villageName: '',
    harvestAddressList: [
      {
        villageName: '小区',
        houseNumber: '123123',
        linkName: '小明',
        phone: '4564646'
      },
      {
        villageName: '小区',
        houseNumber: '123123',
        linkName: '小黑',
        phone: '4564646'
      },
      {
        villageName: '小区',
        houseNumber: '123123',
        linkName: '小白',
        phone: '4564646'
      }
    ],
    showHarvestAddress: false,
    harvestAddress: '',
    harvestAddressLinkName: '',
    harvestAddressPhone: '',
    displayHarvestAddress: false, // 页面上是否显示收货地址
    displayResidentAddress: false, // 页面上是否显示住户
    residentAddress: '' // 呼叫器栋单元层的地址
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad(options) {
    let scene = decodeURIComponent(options.scene);
    if (scene != 'undefined') {
      // 有scene代表扫码进的小程序
      this.beeperCode = scene.split('hc=')[1];
      app.isLogin(this.getEquipInfo);
    } else {
      this.beeperCode = options.hc;
      app.isLogin(this.getEquipInfo);
    }
  },
  /**
   * 生命周期函数--监听页面显示
   */
  onShow() {},
  // 获取手机号
  async getPhoneNumber(e) {
    const {
      detail: { code },
      currentTarget: {
        dataset: { type }
      }
    } = e;
    let cond = {
      code,
      appId: Storage.APPID
    };
    if (cond.code) {
      let res = await $api.getPhone(cond);
      res = res.data.data;
      if (!res) return;
      let prop = type == 1 ? 'phone' : 'harvestAddressPhone';
      this.setData({
        [prop]: res,
        typeTag: 1
      });
    }
  },
  // 判断当前是否已绑定呼叫器
  async getEquipInfo() {
    let params = {
      code: this.beeperCode
    };
    try {
      const res = await $api.getEquipInfo(params);
      let data = res.data.data;
      if (data) {
        this.setData({
          beeperAddress: data.beeperAddress,
          equipCode: data.equipCode,
          equipId: data.equipId,
          equipType: data.equipType,
          beeperType: data.beeperType,
          beeperVersion: data.beeperVersion,
          beeperBinding: data.beeperBinding,
          beeperId: data.relationId,
          addressType: data.addressType,
          unitId: data.unitId,
          unitName: data.unitName,
          buildName: data.buildName,
          buildId: data.buildId,
          requireAddress: data.requireAddress,
          existZhu: data.main ? true : false // 有主用户，如果main不存在就没有主用户
        });
        const modifyData = {
          residentAddressTitle: ''
        };
        const { addressType } = data;
        if (data.beeperBinding) {
          // 如果绑定了就直接跳首页
          // app.globalData.beeperId = this.data.beeperId
          // 设备页面重新获取一下设备列表
          const page = getCurrentPages().find(item => item.route == 'pages/equipment/index');
          page && page.getList();
          wx.reLaunch({
            url: '/pages/home/index?beeperId=' + data.relationId
          });
          return;
        } else if (data.main) {
          // 地址类型是1或者3或者requireAddress等于2(等于2表示呼叫器下单时绑定)的时候直接绑定
          if (addressType == 1 || addressType == 3 || data.requireAddress == 2) return this.bindingSubmit(false);
          if (addressType == 5) this.getHarvestAddressList();
          if (addressType != 1 && addressType != 3 && addressType != 5) {
            // 2 4 6 7 8
            modifyData.residentAddress = data.villageName || '';
            switch (addressType) {
              case 2:
                modifyData.residentAddress =
                  modifyData.residentAddress +
                  (data.buildName || '') +
                  (data.unitName || '') +
                  (data.floorName || '') +
                  (data.houseNumber || '');
                break;
              // break
              case 4:
                modifyData.residentAddress =
                  modifyData.residentAddress + (data.buildName || '') + (data.unitName || '') + (data.floorName || '');
                break;
              case 6:
                modifyData.residentAddress =
                  modifyData.residentAddress + (data.buildName || '') + (data.unitName || '');
              case 7:
                modifyData.residentAddress = modifyData.residentAddress + (data.buildName || '');
            }
          }

          modifyData.displayResidentAddress = addressType == 6 || addressType == 7 || addressType == 8;
          if (modifyData.displayResidentAddress) {
            if (addressType == 6) {
              this.getResidentAddressList({
                parentId: data.unitId
              });
            } else if (addressType == 7) {
              this.getResidentAddressList({
                parentId: data.buildId
              });
            } else if (addressType == 8) {
              this.getResidentAddressList({
                villageId: data.villageId
              });
            }
          }
          modifyData.displayHarvestAddress =
            addressType == 2 || addressType == 4 || addressType == 5 || modifyData.displayResidentAddress;

          modifyData.displayHouseNumber = modifyData.displayResidentAddress || addressType == 4 || addressType == 5;
          switch (addressType) {
            case 6:
              modifyData.residentAddressTitle = '请选择层、门牌号';
              break;
            case 7:
              modifyData.residentAddressTitle = '请选择单元、层、门牌号';
              break;
            case 8:
              modifyData.residentAddressTitle = '请选择栋、单元、层、门牌号';
              break;
          }
        } else if (!data.main) {
          // 不存在主用户
          this.localeList();
          if (addressType != 1 && addressType != 5) {
            modifyData.residentAddress =
              (data.villageName || '') +
              (data.buildName || '') +
              (data.unitName || '') +
              (data.floorName || '') +
              (data.houseNumber || '');
          }
          if (addressType == 4 || addressType == 6 || addressType == 7 || addressType == 8) {
            // 地址类型是4678的时候用呼叫器的地址
            modifyData.provinceName = data.provinceName;
            modifyData.cityName = data.cityName;
            modifyData.areaName = data.areaName;
            modifyData.streetName = data.streetName;
            modifyData.longitude = data.longitude;
            modifyData.latitude = data.latitude;
          }
        }
        modifyData.loading = false;
        // 这里获取用户本地存储的手机号和联系人
        modifyData.storageLinkName = wx.getStorageSync(Storage.NICK_NAME);
        modifyData.storagePhone = wx.getStorageSync(Storage.PHONE);
        this.setData(modifyData);
      }
    } catch (err) {
      setTimeout(() => {
        wx.switchTab({
          url: '/pages/home/index'
        });
      }, 2000);
    }
  },
  // 获取收货地址
  async getHarvestAddressList() {
    let res = await $api.addressList({});
    res = res.data.data || [];
    res.forEach(item => {
      item.villageName = item.villageName || '';
      item.address = item.address || '';
    });
    this.setData({
      harvestAddressList: res
    });
  },
  showHarvestAddressPopup() {
    this.setData({
      showHarvestAddress: true
    });
  },
  confirmHarvestAddress(e) {
    const { streetName, areaName, cityName, provinceName, latitude, longitude, villageName, address } =
      e.currentTarget.dataset.item;
    this.setData({
      streetName,
      areaName,
      cityName,
      provinceName,
      harvestAddress: address,
      longitude,
      latitude,
      villageName
    });
    this.closeHarvestAddress();
  },
  closeHarvestAddress() {
    this.setData({
      showHarvestAddress: false
    });
  },
  // 选择收货地址
  async selectHarvestAddress() {
    let res = await wx.chooseLocation();
    if (!res) return;
    const { latitude, longitude } = res;
    res = await getAddress(latitude, longitude);
    const {
      address_component: { street, district, city, province },
      formatted_addresses: { recommend }
    } = res;

    this.setData({
      streetName: street,
      areaName: district,
      cityName: city,
      provinceName: province,
      latitude,
      longitude,
      villageName: '',
      harvestAddress: recommend
    });
    this.closeHarvestAddress();
  },
  // 获取场所列表
  async localeList() {
    let res = await $api.localeList({
      beeperId: this.data.beeperId
    });
    res = res.data.data || [];
    const modifyData = {};
    if (res.length) {
      modifyData.columnsCS = res.concat([
        {
          id: -1,
          name: '自定义场所'
        }
      ]);
    } else {
      modifyData.showCustomLocale = true;
    }
    this.setData(modifyData);
  },
  async getAccountInfo(e) {
    const { type } = e.currentTarget.dataset;
    const modifyData = {};
    const { storageLinkName, storagePhone } = this.data;
    if (type == '1') {
      modifyData.phone = storagePhone;
      // modifyData.linkName = storageLinkName
    } else if (type == '2') {
      modifyData.harvestAddressPhone = storagePhone;
      // modifyData.harvestAddressLinkName = storageLinkName
    }
    this.setData(modifyData);
  },
  //************************************************************************************************************* */
  /**
   * 地址类型是678中的一个：门牌号(存在必填字段就必填否则比用必填)、电话号码(必填)、住户地址(存在必填字段就必填否则比用必填)
   * 如果不存在主用户：场所(必填)、安装区域(必填)、门牌号(必填)、电话号码(公共呼叫器必填)、联系人(公共呼叫器必填),
   * 如果存在主用户地址类型不是678中的一个就直接绑定
   */
  // 提交绑定检查
  checkSubmit() {
    const regex = /^\d{1,12}$/;
    // 场所名称是否存在
    const {
      existZhu,
      beeperType,
      localeName,
      installArea,
      houseNumber,
      linkName,
      phone,
      harvestAddressLinkName,
      harvestAddressPhone,
      displayHouseNumber,
      displayResidentAddress,
      residentAddressTitle,
      displayHarvestAddress,
      addressType,
      harvestAddress,
      villageName,
      floorId
    } = this.data;
    console.log(displayHarvestAddress, addressType, harvestAddress);
    if (!existZhu) {
      // 不存在主用户
      if (!localeName) {
        Toast.fail('请输入或选择安装场所');
        return;
      }
      if (!installArea) {
        Toast.fail('请输入或选择安装区域');
        return;
      }
      if (!linkName) {
        Toast.fail('请填写联系人');
        return;
      }
      if (!phone) {
        Toast.fail('请填写联系电话');
        return;
      }
      if (!regex.test(phone)) {
        Toast('联系电话格式不正确');
        return;
      }
    } else if (displayHarvestAddress) {
      if (displayResidentAddress && !floorId) {
        Toast.fail(residentAddressTitle);
        return;
      }
      if (addressType == 5 && !harvestAddress && !villageName) {
        Toast.fail('请填写收货地址');
        return;
      }
      if (displayHouseNumber && !houseNumber) {
        Toast.fail('请填写门牌号');
        return;
      }
      // 且是绑定时候填写地址
      if (!harvestAddressLinkName) {
        Toast.fail('请填写收货地址联系人');
        return;
      }
      if (!harvestAddressPhone) {
        Toast.fail('请填写收货地址联系电话');
        return;
      }
      if (!regex.test(harvestAddressPhone)) {
        Toast('收货地址联系电话格式不正确');
        return;
      }
    }
    return true;
  },
  // 绑定提交
  async bindingSubmit(check = true) {
    if (check && !this.checkSubmit()) return;
    const {
      existZhu,
      equipId,
      localeId,
      localeName,
      houseNumber,
      houseNumberId,
      installArea,
      linkName,
      phone,
      addressType,
      requireAddress,
      unitName,
      unitId,
      buildId,
      buildName,
      floorId,
      floorName,
      harvestAddressPhone,
      harvestAddressLinkName,
      harvestAddress,
      provinceName,
      cityName,
      areaName,
      streetName,
      latitude,
      longitude,
      displayHouseNumber,
      displayResidentAddress,
      villageName,
      typeTag,
      beeperId
    } = this.data;
    let params = {
      equipId
    };
    if (!existZhu) {
      // 存在主用户
      params.installArea = installArea;
      params.localeId = localeId > 0 ? localeId : '';
      !params.localeId && (params.localeNickName = localeName);
      params.linkName = linkName;
      params.phone = phone;
    } else if (existZhu && requireAddress == 1) {
      if (addressType == 5) {
        const userAddress = {};
        userAddress.provinceName = provinceName;
        userAddress.cityName = cityName;
        userAddress.areaName = areaName;
        userAddress.streetName = streetName;
        userAddress.longitude = longitude;
        userAddress.latitude = latitude;
        userAddress.linkName = harvestAddressLinkName;
        userAddress.phone = harvestAddressPhone;
        userAddress.houseNumber = houseNumber;
        userAddress.address = harvestAddress;
        villageName && (userAddress.villageName = villageName);
        params.userAddress = userAddress;
      } else {
        params.linkName = harvestAddressLinkName;
        params.phone = harvestAddressPhone;
        if (displayHouseNumber) {
          params.houseNumber = houseNumber;
          params.houseNumberId = houseNumberId;
        }
        if (displayResidentAddress) {
          params.buildId = buildId;
          params.buildName = buildName;
          params.unitId = unitId;
          params.unitName = unitName;
          params.floorId = floorId;
          params.floorName = floorName;
        }
      }
    }
    let res = await $api.equipBinding(params);
    typeTag && wx.setStorageSync(Storage.PHONE, params.phone);
    if (res.data.status == 0) {
      if (check) Toast.success('绑定成功');
      setTimeout(() => {
        // 全局保存绑定的呼叫器id，跳到首页的时候调用
        // app.globalData.beeperId = this.data.beeperId
        wx.reLaunch({
          url: '/pages/home/index?beeperId=' + beeperId
        });
      }, 1000);
    }
  },
  // 选择场所
  selectLocale(e) {
    let id = e.target.dataset.id;
    if (!id) return;
    let temp = this.data.columnsCS.find(item => item.id == id);
    if (temp.id == this.data.columnsCS[this.data.columnsCS.length - 1].id) {
      this.setData({
        localeId: id,
        localeName: '',
        showCustomLocale: true
      });
    } else {
      this.setData({
        localeId: id,
        localeName: temp.name,
        showCustomLocale: false
      });
    }
  },
  // 输入自定义场所
  inputLocale(e) {
    this.setData({
      localeName: e.detail.value
    });
  },
  // 获取栋单元层列表
  async getResidentAddressList(params) {
    let res = await $api.getResidentAddressList(params);
    res = res.data.data || [];
    deEmptyChildrenCascader(res);
    const options = res.map(item => {
      return { ...item, children: [] };
    });
    this.setData({ residentAddressList: res, residentAddressOptions: options });
  },
  showResidentAddressPopup() {
    this.setData({
      showResidentAddress: true
    });
  },
  confirmResidentAddress(e) {
    const { selectedOptions } = e.detail;
    console.log(selectedOptions);
    const houseNumber = selectedOptions.at(-1);
    const floor = selectedOptions.at(-2);
    const unit = selectedOptions.at(-3);
    const build = selectedOptions.at(-4);

    const modifyData = {
      residentAddressName: '',
      residentAddressValue: ''
    };
    if (build) {
      modifyData.buildId = build.id;
      modifyData.buildName = build.name;
      modifyData.residentAddressName = build.name;
      modifyData.residentAddressValue = build.id;
    }
    if (unit) {
      modifyData.unitId = unit.id;
      modifyData.unitName = unit.name;
      modifyData.residentAddressValue = unit.id;
      modifyData.residentAddressName = modifyData.residentAddressName
        ? modifyData.residentAddressName + '/' + unit.name
        : unit.name;
    }
    if (floor) {
      modifyData.floorId = floor.id;
      modifyData.floorName = floor.name;
      modifyData.residentAddressValue = floor.id;
      modifyData.residentAddressName = modifyData.residentAddressName
        ? modifyData.residentAddressName + '/' + floor.name
        : floor.name;
    }
    if (houseNumber) {
      modifyData.houseNumberId = houseNumber.id;
      modifyData.houseNumber = houseNumber.name;
      modifyData.residentAddressValue = houseNumber.id;
      modifyData.residentAddressName = modifyData.residentAddressName
        ? modifyData.residentAddressName + '/' + houseNumber.name
        : houseNumber.name;
    }
    this.setData(modifyData);
    this.closeResidentAddress();
  },
  closeResidentAddress() {
    this.setData({
      showResidentAddress: false
    });
  },
  // 选择小区
  async showVillagePopup() {
    const { provinceId, cityId, areaId, streetId } = this.data;
    if (!provinceId) return Toast.fail('请先选择省市区街道');
    let res = await $api.getListVillage({
      provinceId,
      cityId,
      areaId,
      streetId
    });
    this.setData({
      showVillage: true,
      villageList: res.data.data || []
    });
  },
  // 确定选择小区
  confirmSelectVillage(e) {
    const { value } = e.detail;
    this.setData({
      villageId: value.id || '',
      villageName: value.name || ''
    });
  },
  // 选择安装区域
  selectArea(e) {
    let index = e.target.dataset.index;
    if (!index && index !== 0) return;
    if (index == this.data.columnsQY.length - 1) {
      this.setData({
        customArea: true,
        installArea: '',
        areaIndex: index,
        showCustomArea: true
      });
    } else {
      this.setData({
        installArea: this.data.columnsQY[index],
        areaIndex: index,
        showCustomArea: false
      });
    }
  },
  // 输入安装区域
  installAreaInput(e) {
    this.setData({
      installArea: e.detail.value
    });
  },
  // 门牌号输入
  handleInput(e) {
    const {
      detail: { value },
      currentTarget: {
        dataset: { prop }
      }
    } = e;
    this.setData({
      [prop]: value
    });
  },
  // 取消
  cancelBtn() {
    setTimeout(() => {
      wx.switchTab({
        url: '/pages/home/index'
      });
    }, 1000);
  },
  // 自定义场所输入绑定
  localeNameInput(e) {
    let value = e.detail.value;
    this.setData({
      localeName: value
    });
  },
  /**
   * 地址选择器change
   */
  handleCascaderChange(e) {
    const { value, tabIndex, selectedOptions } = e.detail;
    const { residentAddressList, residentAddressOptions } = this.data;
    if (tabIndex === 0) {
      const selectedOption = findPathDFS(residentAddressList, value).children.map(c => {
        return { ...c, children: [] };
      });
      const index = residentAddressOptions.findIndex(c => c.id === value);
      this.setData({ [`residentAddressOptions[${index}].children`]: selectedOption });
    }
    if (tabIndex === 1) {
      const selectedOption = findPathDFS(residentAddressList, value).children.map(c => {
        return { ...c, children: [] };
      });
      const index = residentAddressOptions.findIndex(c => c.id === selectedOptions[0].id);
      const childrenIndex = residentAddressOptions[index].children.findIndex(c => c.id === value);
      this.setData({ [`residentAddressOptions[${index}].children[${childrenIndex}].children`]: selectedOption });
    }
    if (tabIndex === 2) {
      const selectedOption = findPathDFS(residentAddressList, value);
      const index = residentAddressOptions.findIndex(c => c.id === selectedOptions[0].id);
      const childrenIndex = residentAddressOptions[index].children.findIndex(c => c.id === selectedOptions[1].id);
      const children2Index = residentAddressOptions[index].children[childrenIndex].children.findIndex(
        c => c.id === selectedOptions[2].id
      );
      this.setData({
        [`residentAddressOptions[${index}].children[${childrenIndex}].children[${children2Index}]`]: selectedOption
      });
    }
  }
});
